<template>
  <div class="app-container">
    <el-card class="box-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">商品列表</span>
          <div class="right-toolbar">
            <el-upload
              class="excel-upload"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleExcelChange"
            >
              <el-button
                type="success"
                plain
                icon="Upload"
                class="action-button"
              >上传Excel</el-button>
            </el-upload>
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleBatchDelete"
              class="action-button"
            >批量删除</el-button>
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              class="add-button"
            >新增</el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true">
          <el-form-item label="商品名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入商品名称"
              clearable
              @keyup.enter="handleQuery"
              @clear="handleQuery"
              class="search-input"
            />
          </el-form-item>
          <el-form-item label="SKU" prop="sku">
            <el-input
              v-model="queryParams.sku"
              placeholder="请输入SKU"
              clearable
              @keyup.enter="handleQuery"
              @clear="handleQuery"
              class="search-input"
            />
          </el-form-item>
          <el-form-item label="状态" prop="offShelf" v-if="false">
            <el-select
              v-model="queryParams.offShelf"
              placeholder="请选择状态"
              clearable
              @change="handleQuery"
              class="search-input"
            >
              <el-option label="上架" :value="0" />
              <el-option label="下架" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          border
          stripe
          highlight-current-row
          @selection-change="handleSelectionChange"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          row-class-name="table-row"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            prop="id"
            label="ID"
            width="80"
            align="center"
          />
          <el-table-column
            prop="name"
            label="商品名称"
            min-width="180"
            show-overflow-tooltip
          />
          <el-table-column
            prop="sku"
            label="SKU"
            width="100"
            align="center"
            >
          </el-table-column>
          <el-table-column
            prop="price"
            label="价格"
            width="100"
            align="center"
          >
            <template #default="scope">
              <span class="price-tag">¥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="channel"
            label="渠道"
            width="100"
            align="center"
          />
          <el-table-column
            prop="link"
            label="链接"
            width="120"
            align="center"
          >
            <template #default="scope">
              <el-link type="primary" :href="scope.row.link" target="_blank" :underline="false">查看链接</el-link>
            </template>
          </el-table-column>
          <el-table-column
            prop="taocode"
            label="淘口令"
            width="120"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="image"
            label="图片"
            width="120"
            align="center"
          >
            <template #default="scope">
              <ImagePreview
                v-if="scope.row.image"
                :src="scope.row.image"
                :width="80"
                :height="80"
                fit="cover"
                :lazy="true"
                class="table-image-preview"
              />
              <div v-else class="image-placeholder">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="itemId"
            label="商品ID"
            width="120"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="offShelf"
            label="状态"
            width="100"
            align="center"
          >
            <template #default="scope">
              <el-tag :type="scope.row.offShelf === 0 ? 'success' : 'danger'">
                {{ scope.row.offShelf === 0 ? '上架' : '下架' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="180"
            align="center"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="handleEdit(scope.row)"
                class="action-button"
              >编辑</el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row)"
                class="action-button"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <el-pagination
          class="pagination"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
          background
        />
      </div>
    </el-card>

    <!-- 添加或修改对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="550px"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      class="product-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="product-form"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" clearable>
            <template #prefix>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="渠道" prop="channel">
          <el-input v-model="form.channel" placeholder="请输入渠道" clearable />
        </el-form-item>
        <el-form-item label="SKU" prop="sku">
          <el-input v-model="form.sku" placeholder="请输入SKU" clearable />
        </el-form-item>
        <el-form-item label="链接" prop="link">
          <el-input v-model="form.link" placeholder="请输入链接" clearable />
        </el-form-item>
        <el-form-item label="淘口令" prop="taocode">
          <el-input v-model="form.taocode" placeholder="请输入淘口令" clearable type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-input v-model="form.image" placeholder="请输入图片URL" clearable />
          <div class="image-preview" v-if="form.image">
            <ImagePreview :src="form.image" :width="120" :height="120" fit="cover" class="form-image-preview" />
          </div>
        </el-form-item>
        <el-form-item label="商品ItemID" prop="itemId">
          <el-input v-model="form.itemId" placeholder="请输入商品ItemID" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="offShelf" v-if="false">
          <el-radio-group v-model="form.offShelf">
            <el-radio :label="0">上架</el-radio>
            <el-radio :label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel" plain>取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listProducts, addProduct, updateProduct, delProduct, getProduct, uploadProducts } from '@/api/product/index'
import { Picture } from '@element-plus/icons-vue'
import ImagePreview from '@/components/ImagePreview/index.vue'

// 遮罩层
const loading = ref(false)
// 总条数
const total = ref(0)
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  sku: '',
  offShelf: undefined
})

// 表单参数
const form = reactive({
  id: undefined,
  name: '',
  price: undefined,
  sku: '',
  channel: '淘宝商城',
  link: '',
  taocode: '',
  image: '',
  itemId: '',
  offShelf: 0
})

// 表单校验规则
const rules = {
  name: [
    { required: false, message: '商品名称不能为空', trigger: 'blur' }
  ],
  price: [
    { required: false, message: '价格不能为空', trigger: 'blur' }
  ],
  sku: [
    { required: true, message: 'SKU不能为空', trigger: 'blur' }
  ],
  channel: [
    { required: false, message: '渠道不能为空', trigger: 'blur' }
  ],
  link: [
    { required: true, message: '链接不能为空', trigger: 'blur' }
  ],
  taocode: [
    { required: true, message: '淘口令不能为空', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '图片不能为空', trigger: 'blur' }
  ],
  itemId: [
    { required: true, message: '商品ID不能为空', trigger: 'blur' }
  ]
}

// 表格数据
const tableData = ref([])

// 表单ref
const formRef = ref()
// 查询表单ref
const queryFormRef = ref()

/** 查询列表 */
function getList() {
  loading.value = true
  listProducts(queryParams).then(response => {
    tableData.value = response.data.list
    total.value = response.data.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.id = undefined
  form.name = ''
  form.price = undefined
  form.sku = ''
  form.channel = '淘宝商城'
  form.link = ''
  form.taocode = ''
  form.image = ''
  form.itemId = ''
  form.offShelf = 0
  formRef.value?.resetFields()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加商品'
}

/** 修改按钮操作 */
function handleEdit(row) {
  reset()
  const id = row.id || row
  getProduct(id).then(response => {
    Object.assign(form, response.data)
    open.value = true
    title.value = '修改商品'
  })
}

/** 提交按钮 */
function submitForm() {
  formRef.value?.validate((valid) => {
    if (valid) {
      const formData = new FormData()
      // 遍历form对象，将数据添加到FormData中
      Object.keys(form).forEach(key => {
        if (form[key] !== undefined && form[key] !== null) {
          if (key === 'price') {
            formData.append(key, Number(form[key]))
          } else {
            formData.append(key, form[key])
          }
        }
      })
      
      const operationType = form.id ? '修改' : '新增'
      const apiFunc = form.id ? updateProduct : addProduct
      
      loading.value = true
      apiFunc(formData).then(() => {
        ElMessage.success(`${operationType}成功`)
        open.value = false
        getList()
      }).catch(() => {
        ElMessage.error(`${operationType}失败`)
      }).finally(() => {
        loading.value = false
      })
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const idsToDelete = row.id || ids.value
  
  ElMessageBox.confirm(`是否确认删除商品编号为"${idsToDelete}"的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    return delProduct(idsToDelete)
  }).then(() => {
    getList()
    ElMessage.success('删除成功')
  }).catch(error => {
    console.log(error)
    ElMessage.error('删除失败')
  }).finally(() => {
    loading.value = false
  })
}

/** 批量删除按钮操作 */
function handleBatchDelete() {
  if (ids.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(`是否确认批量删除选中的${ids.value.length}条数据?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    // 这里的API需要支持批量删除，传入的是一个数组或逗号分隔的字符串
    return delProduct(ids.value.join(','))
  }).then(() => {
    getList()
    ElMessage.success('批量删除成功')
  }).catch(error => {
    console.log(error)
    if (error !== 'cancel') ElMessage.error('批量删除失败')
  }).finally(() => {
    loading.value = false
  })
}

/** 选择条目触发事件 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 分页大小改变 */
function handleSizeChange(val) {
  queryParams.pageSize = val
  getList()
}

/** 分页页码改变 */
function handleCurrentChange(val) {
  queryParams.pageNum = val
  getList()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  queryParams.pageNum = 1
  getList()
}

/** 上传前校验 */
function validateExcelFile(file) {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isExcel) {
    ElMessage.error('上传文件只能是Excel文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('上传文件大小不能超过 5MB!')
    return false
  }
  return true
}

/** 处理Excel文件选择 */
function handleExcelChange(file) {
  if (!file || !file.raw) return
  
  if (!validateExcelFile(file.raw)) return
  
  loading.value = true
  uploadProducts(file.raw).then(response => {
    if (response.code === "00000") {
      const count = response.data?.count || 0
      ElMessage.success(`上传成功，共导入 ${count} 条记录`)
      getList()
    } else {
      ElMessage.error(response.msg || '上传失败')
    }
  }).catch(error => {
    console.error('Excel上传失败:', error)
    ElMessage.error('上传失败，请重试')
  }).finally(() => {
    loading.value = false
  })
}

// 初始化数据
getList()
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.right-toolbar {
  display: flex;
  gap: 10px;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  position: relative;
  padding-left: 12px;
}

.card-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: #409EFF;
  border-radius: 2px;
}

.add-button, .action-button {
  transition: all 0.3s;
  border-radius: 4px;
}

.add-button:hover, .action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.table-container {
  margin-top: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.table-row {
  transition: all 0.2s;
}

.table-row:hover {
  background-color: #f0f9ff !important;
}

.pagination {
  margin-top: 25px;
  justify-content: flex-end;
  padding-bottom: 10px;
}

.table-image-preview {
  margin: 0 auto;
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}

.table-image-preview:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.image-placeholder {
  width: 70px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 6px;
  color: #909399;
  font-size: 24px;
  margin: 0 auto;
  border: 1px dashed #dcdfe6;
}

.price-tag {
  color: #f56c6c;
  font-weight: bold;
  background-color: #fff0f0;
  padding: 4px 8px;
  border-radius: 12px;
  display: inline-block;
  font-size: 14px;
}

.action-button {
  padding: 4px 8px;
  margin: 0 5px;
  font-size: 13px;
}

.product-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 16px 20px;
  margin-right: 0;
  background-color: #f5f7fa;
}

.product-dialog :deep(.el-dialog__title) {
  font-weight: bold;
  color: #303133;
  font-size: 16px;
}

.product-dialog :deep(.el-dialog__body) {
  padding: 24px 25px;
}

.product-dialog :deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 16px 20px;
  background-color: #f5f7fa;
}

.product-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.product-form :deep(.el-form-item__label) {
  font-weight: 500;
}

.product-form :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.product-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.product-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409EFF inset;
}

.product-form::-webkit-scrollbar {
  width: 6px;
}

.product-form::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.product-form::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

.image-preview {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.form-image-preview {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.excel-upload {
  display: inline-block;
}

.search-container {
  background-color: #f8f9fb;
  border-radius: 4px;
  padding: 18px;
  margin-bottom: 20px;
  box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.03);
}

.search-input {
  width: 240px;
}

.search-container :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 20px;
}

.search-container :deep(.el-button) {
  transition: all 0.3s;
}

.search-container :deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>